import React, { ClassAttributes } from 'react';
import _ from 'lodash';
import * as SysApi from '../sys.api';
import * as SysBom from '../sys.bom';
import * as SignInApi from './sign-in';
import * as UserApi from './user';

SignInApi.register();
UserApi.register();

interface ISignInStatusState {
    // 当前用户名。
    name: string,
    // 当前用户是否已认证。
    authenticated: boolean,
}

class SignInStatus extends React.Component<{}, ISignInStatusState> {
    constructor(props: {}) {
        super(props);

        this.state = {
            name: '',
            authenticated: false,
        };
    }

    componentDidMount = () => {
        SysApi.call('user.current')
            .then(data => {
                this.setState({
                    name: data.name,
                    authenticated: data.authenticated,
                })
            });
    };

    private handleSignIn = () => {
        SysBom.jumpTo('/sign-in');
    };

    private handleSignOut = () => {
        SysApi.call('security.signOut', null, true)
            .then(data => {
                // 成功注销后，跳转到首页。
                SysBom.jumpTo('/');
            });
    };

    render = (): JSX.Element => {
        const current = (window as any).env.current as string;

        if (this.state.authenticated) {
            return <>
                <span style={{ marginRight: '1rem' }}>欢迎您！{this.state.name}</span>
                <span style={{ cursor: 'pointer' }} onClick={this.handleSignOut} ><i className="sign-out icon" />注销</span>
            </>;
        } else {
            return <>
                <span style={{ cursor: 'pointer' }} onClick={this.handleSignIn} ><i className="sign-in icon" />登录</span>
            </>;
        }
    };
}

export { SignInStatus };